
namespace C4F.DevKit.Contacts.Standard
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Runtime.InteropServices;
    using System.Windows;
    using System.Windows.Interop;
    using System.Windows.Media;

    internal class GlassHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct MARGINS
        {
            public MARGINS(Thickness t)
            {
                cxLeftWidth = (int)t.Left;
                cxRightWidth = (int)t.Right;
                cyTopHeight = (int)t.Top;
                cyBottomHeight = (int)t.Bottom;
            }

            /// <summary>Width of left border that retains its size.</summary>
            public int cxLeftWidth;
            /// <summary>Width of right border that retains its size.</summary>
            public int cxRightWidth;
            /// <summary>Height of top border that retains its size.</summary>
            public int cyTopHeight;
            /// <summary>Height of bottom border that retains its size.</summary>
            public int cyBottomHeight;
        };

        [DllImport("DwmApi.dll", PreserveSig = false)]
        private static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS pMarInset);

        [DllImport("DwmApi.dll", PreserveSig = false)]
        private static extern bool DwmIsCompositionEnabled();

        public static bool ExtendGlassFrameComplete(Window window)
        {
            return ExtendGlassFrame(window, new Thickness(-1));
        }

        // Actually this looks rather funky when not using a Thickness of -1 -- use with care.
        public static bool ExtendGlassFrame(Window window, Thickness margin)
        {
            if (!DwmIsCompositionEnabled())
            {
                return false;
            }

            IntPtr hwnd = new WindowInteropHelper(window).Handle;
            if (IntPtr.Zero == hwnd)
            {
                throw new InvalidOperationException("Window must be shown before extending glass.");
            }

            // Apply the transparent background to both the Window and HWND
            window.Background = Brushes.Transparent;
            HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent;
            
            MARGINS dwmMargin = new MARGINS(margin);
            DwmExtendFrameIntoClientArea(hwnd, ref dwmMargin);

            return true;
        }
    }
}
